package com.tpc.wdt.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tpc.wdt.WdtClient;
import com.tpc.wdt.utils.JDBCUtil;
import com.tpc.wdt.utils.TableSaveUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class TrOutQueryMidFive {
    @Value("${wdt.sid}")
    private String sid;

    @Value("${wdt.appkey}")
    private String appkey;

    @Value("${wdt.appsecret}")
    private String appsecret;

    @Value("${wdt.url}")
    private String url;

    @Value("${wdt.warehouse_no}")
    private String warehouse_no;

    public void trOutQueryMidFive(){

        WdtClient client = new WdtClient(sid, appkey, appsecret, url);
        int page_size = 100;
        int page_no = 0;
        int count = 0;
        Map<String, String> params = new HashMap<String, String>();
//        params.put("warehouse_no", warehouse_no);
        params.put("start_time",DateUtil.format( DateUtil.offsetMinute(new Date(), -5) ,"yyyy-MM-dd HH:mm:ss") );
//        params.put("start_time", "2025-06-02 00:00:00");
//        params.put("end_time", "2025-05-31 00:00:00");
        params.put("end_time", DateUtil.date().toString());
//        params.put("start_time", "2023-12-12 00:00:00");
//        params.put("end_time", "2023-12-12 23:59:59");
        params.put("page_size",String.valueOf(page_size));
//        params.put("stockout_no","CK202506061022");
        params.put("page_no",String.valueOf(page_no));
        params.put("is_by_modified","0");
        Connection connection = JDBCUtil.getConnection();
//        params.put("status","110");
        try {
            connection.setAutoCommit(false);
            log.info("获取销售出库单参数：{}",params);
            count = page_size;
            String response = client.execute("stockout_order_query_trade.php", params);
            log.info("旺店通返回信息：{}",response);
            JSONObject jsonResponse = JSONObject.parseObject(response);
            if(jsonResponse.getInteger("code")==0){
                JSONArray jsonArray = jsonResponse.getJSONArray("stockout_list");
                JSONArray jsonArrayMt = new JSONArray();
                JSONArray jsonArrayDt = new JSONArray();
                JSONArray jsonArrayBatchDt = new JSONArray();
                for(int i = 0 ;i<jsonArray.size();i++){
                    JSONObject jsonObjectMt = jsonArray.getJSONObject(i);
                    if((jsonObjectMt.getInteger("trade_type")==1 && ( jsonObjectMt.getInteger("trade_status")==95 || jsonObjectMt.getInteger("trade_status")==110))
                            || (jsonObjectMt.getInteger("trade_type")!=1 && jsonObjectMt.getInteger("trade_status")==110)){
                        if(jsonObjectMt.getJSONArray("details_list")!=null){
                            JSONArray jsonArrayDetails = jsonObjectMt.getJSONArray("details_list");
                            for(int j=0;j<jsonArrayDetails.size();j++){
                                jsonArrayDt.add(jsonArrayDetails.getJSONObject(j));
                                if(jsonArrayDetails.getJSONObject(j).getJSONArray("position_list")!=null){
                                    JSONArray jsonArrayBatch = jsonArrayDetails.getJSONObject(j).getJSONArray("position_list");
                                    for(int k=0;k<jsonArrayBatch.size();k++){
                                        jsonArrayBatchDt.add(jsonArrayBatch.getJSONObject(k));
                                    }
                                }
                            }
                        }

                        log.info("获取{}",jsonArrayBatchDt);
                        jsonArrayMt.add(jsonObjectMt);
                    }
                }
                TableSaveUtils.tableSave(connection,"wdt_saleoutmt_new",jsonArrayMt);
                TableSaveUtils.tableSave(connection,"wdt_saleoutdt_new",jsonArrayDt);
                log.info("批号明细：{}",jsonArrayBatchDt);
                TableSaveUtils.tableSave(connection,"WDT_SALEOUTDT_BATCH_NEW",jsonArrayBatchDt);
                int total_count = jsonResponse.getInteger("total_count");

                while (count <= total_count) {
                    if(count == 0) {
                        continue;
                    }
                    log.info("获取销售出库单参数：{}",params);
                    count = count + page_size;
                    page_no = page_no + 1 ;
                    params.put("page_no",String.valueOf(page_no));
                    String twoResponse = client.execute("stockout_order_query_trade.php", params);
                    log.info("旺店通返回信息：{}",twoResponse);
                    JSONObject jsonTwoResponse = JSONObject.parseObject(twoResponse);
                    if(jsonTwoResponse.getInteger("code")==0){
                        JSONArray twoJsonArray = jsonTwoResponse.getJSONArray("stockout_list");
                        JSONArray twoJsonArrayMt = new JSONArray();
                        JSONArray twoJsonArrayDt = new JSONArray();
                        JSONArray towJsonArrayBatchDt = new JSONArray();
                        for(int i = 0 ;i<twoJsonArray.size() ;i++){
                            JSONObject jsonObjectMt = twoJsonArray.getJSONObject(i);
                            if((jsonObjectMt.getInteger("trade_type")==1 && (jsonObjectMt.getInteger("trade_status")==95 || jsonObjectMt.getInteger("trade_status")==110) )
                                    || (jsonObjectMt.getInteger("trade_type")!=1 && jsonObjectMt.getInteger("trade_status")==110)) {
                                if (jsonObjectMt.getJSONArray("details_list") != null) {
                                    JSONArray jsonArrayDetails = jsonObjectMt.getJSONArray("details_list");
                                    for (int j = 0; j < jsonArrayDetails.size(); j++) {
                                        twoJsonArrayDt.add(jsonArrayDetails.getJSONObject(j));
                                        if(jsonArrayDetails.getJSONObject(j).getJSONArray("position_list")!=null){
                                            JSONArray jsonArrayBatch = jsonArrayDetails.getJSONObject(j).getJSONArray("position_list");
                                            for(int k=0;k<jsonArrayBatch.size();k++){
                                                towJsonArrayBatchDt.add(jsonArrayBatch.getJSONObject(k));
                                            }
                                        }
                                    }
                                }

                            }
                            twoJsonArrayMt.add(jsonObjectMt);
                        }
                        log.info("-------{}",twoJsonArrayMt);
                        TableSaveUtils.tableSave(connection,"WDT_SALEOUTMT_NEW",twoJsonArrayMt);
                        TableSaveUtils.tableSave(connection,"WDT_SALEOUTDT_NEW",twoJsonArrayDt);
                        log.info("批号明细：{}",towJsonArrayBatchDt);
                        TableSaveUtils.tableSave(connection,"WDT_SALEOUTDT_BATCH_NEW",towJsonArrayBatchDt);

                    }
                    if (count > total_count) {
                        break;
                    }
                }
            }
            connection.commit();
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            e.printStackTrace();


            // TODO Auto-generated catch block

        } finally {
            JDBCUtil.close(connection);
        }
    }
}
